package com.github.matrix.common;

/**
 * @author zhaoguoxin
 */
public class TrieTree {


    private TrieNode root;

    public void insert(String word) {
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++) {
            char cur = word.charAt(i);
            if (!node.containsKey(cur)) {
                node.put(cur, new TrieNode());
            }
            node = node.get(cur);
        }
        node.setEnd();
    }
    public boolean search(String word) {
        TrieNode node = searchPrefix(word);
        return node != null && node.isEnd();
    }

    private TrieNode searchPrefix(String word) {
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++) {
            char currChar = word.charAt(i);
            if (node.containsKey(currChar)) {
                node = node.get(currChar);
            } else {
                return null;
            }
        }
        return node;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode node = searchPrefix(prefix);
        return node != null;
    }


    public static class TrieNode {
        private TrieNode[] links;
        private boolean end;
        private final int R = 26;

        public TrieNode() {
            links = new TrieNode[R];
        }
        public boolean containsKey(char c) {
            return links[c - 'a'] != null;
        }
        public TrieNode get(char c) {
            return links[c - 'a'];
        }
        public void put(char c, TrieNode node) {
            links[c - 'a'] = node;
        }
        public void setEnd() {
            end = true;
        }

        public boolean isEnd() {
            return end;
        }
    }
}
